/**
 * 改良版导航render组件，可递归更深层次菜单项
 */
export default {
  name: 'test',
  props: {
    navs: {
      type: Array,
      required: true
    }
  },
  methods: {
    onSelect (curIndex, indexArr) {
      let navItem = this.navs
      let indexs

      // 确保不论路由嵌套多深都可以正确取到path
      indexArr.forEach((item, index) => {
        indexs = item.split('-')
        // '+' 隐式转换为number
        navItem = navItem[+indexs[index]].children || navItem[+indexs[index]]
      }, this)

      this.$emit('click', navItem)
    }
  },
  render (h) {
    /**
     * 递归解析所有子菜单
     * @param {String} top 上一层菜单索引
     * @return jsx DOM数组
     */
    function getSubMenu (navs, top) {
      let topIndex = top ? top + '-' : ''
      let navArr = []
      navs.forEach((item, index) => {
        if (!item.children) {
          navArr.push(
            <el-menu-item
              index={topIndex + index}
              key={index}
            >
              <i class={item.iconClass || ''}></i>
              { item.name }
            </el-menu-item>
          )
        } else {
          navArr.push(
            <el-submenu
              index={topIndex + index}
              key={index}
            >
              <template slot="title">
                <i class={item.iconClass || ''}></i>
                { item.name }
              </template>
              { getSubMenu(item.children, topIndex + index) }
            </el-submenu>
          )
        }
      })
      return navArr
    }

    return (
      <div>
        <el-menu defaultActive="0" theme="dark" onSelect={this.onSelect} >
          { getSubMenu(this.navs) }
        </el-menu>
      </div>
    )
  }
}
